package com.wHitE.servlet;

import com.google.gson.Gson;
import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonParser;
import com.wHitE.utils.Result;
import com.wHitE.service.DeleteBookService;
import com.wHitE.service.impl.DeleteBookServiceImpl;
import jakarta.servlet.ServletConfig;
import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.PrintWriter;

@WebServlet("/deleteBook")
public class DeleteBookServlet extends HttpServlet {
    private DeleteBookService deleteBookService = new DeleteBookServiceImpl();

    @Override
    public void init(ServletConfig config) throws ServletException {
        System.out.println("删除书籍信息接口初始化...");
        super.init(config);
    }

    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        System.out.println("删除书籍信息接口调用...");
        super.service(req, resp);
    }

    @Override
    protected void doDelete(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        // 获取out对象
        PrintWriter out = resp.getWriter();

        String id = req.getParameter("id");
        String[] ids = req.getParameterValues("id");

        // 初始化 object=>json 对象
        Gson gson = new Gson();

        //数据流获取信息
        StringBuilder stringBuilder = new StringBuilder();
        BufferedReader reader = req.getReader();
        char[] buf = new char[1024];
        int len;
        while ((len = reader.read(buf)) != -1) {
            stringBuilder.append(buf, 0, len);
        }
        // 关闭字符输入流
        reader.close();
        // 将可变字符串转为字符串
        String str = stringBuilder.toString();
        JsonArray idsJSON;
        String msg = "";

        if (id == null) {
            // 请求体参数处理
            if (!str.isEmpty()) {
                // 以下方式通过解析json字符串,获取参数值并转换为需要的数据类型
                // 实例化json解析对象
                JsonParser parser = new JsonParser();
                // 实例化json对象元素
                JsonElement element = parser.parse(str);
                // 获取并转换为所需的数据类型
                try {
                    id = element.getAsJsonObject().get("id").getAsString();
                    msg = deleteBookService.deleteBook(Integer.parseInt(id));
                } catch (Exception e) {
                    try {
                        idsJSON = element.getAsJsonObject().getAsJsonArray("id");
                        for (JsonElement ele : idsJSON) {
                            msg = deleteBookService.deleteBook(ele.getAsInt());
                        }
                    } catch (Exception ex) {
                        out.print(gson.toJson(Result.error("请求体参数错误")));
                        return;
                    }
                }
            } else {
                out.print(gson.toJson(Result.error("路径参数错误")));
                return;
            }
        } else {
            // 路径参数处理
            try {
                msg = deleteBookService.deleteBook(Integer.parseInt(id));
            } catch (Exception e) {
                for (String s : ids) {
                    msg = deleteBookService.deleteBook(Integer.parseInt(s));
                }
            }
        }

        // 判断是否请求成功...并响应给前端
        if (msg.equals("success")) {
            out.print(gson.toJson(Result.success()));
        } else {
            out.print(gson.toJson(Result.error(msg)));
        }
    }

    @Override
    public void destroy() {
        System.out.println("删除书籍信息接口关闭...");
    }
}
